package com.kool.kmqtt.server.encoder;

import com.kool.kmqtt.server.packet.Packet;
import com.kool.kmqtt.server.packet.SubackPayload;
import com.kool.kmqtt.server.packet.SubackVariableHeader;

import java.util.List;

/**
 * SUBACK报文编码器
 */
public class SubackPacketEncoder implements PacketEncoder {
    @Override
    public byte[] encode(Packet packet) {
        //固定报头编码
        byte[] fixedHeaderBytes = packet.getFixedHeader().toBytes();

        SubackVariableHeader variableHeader = (SubackVariableHeader) packet.getVariableHeader();
        //可变报头编码
        byte[] variableHeaderBytes = variableHeader.toBytes();

        //载荷
        SubackPayload payload = (SubackPayload) packet.getPayload();
        List<Integer> codes = payload.getCodes();
        byte[] payloadBytes = new byte[codes.size()];
        for (int i = 0; i < codes.size(); i++) {
            payloadBytes[i] = codes.get(i).byteValue();
        }

        //组装报文
        byte[] packetBytes = new byte[fixedHeaderBytes.length + variableHeaderBytes.length + 1];
        System.arraycopy(fixedHeaderBytes, 0, packetBytes, 0, fixedHeaderBytes.length);
        System.arraycopy(variableHeaderBytes, 0, packetBytes, fixedHeaderBytes.length, variableHeaderBytes.length);
        System.arraycopy(payloadBytes, 0, packetBytes, fixedHeaderBytes.length + variableHeaderBytes.length, payloadBytes.length);
        return packetBytes;
    }
}
